package wickethub.repository;

import java.lang.reflect.ParameterizedType;
import java.util.List;

import javax.persistence.EntityManager;

import com.google.inject.Inject;
import com.google.inject.Provider;
import com.wideplay.warp.persist.Transactional;

@SuppressWarnings("unchecked")
abstract class RepositoryImpl<T> implements Repository<T> {

	@Inject
    private Provider<EntityManager> emp;
	private Class<T> persistentClass;
	
	RepositoryImpl() {
		this.persistentClass = (Class<T>) ((ParameterizedType) getClass().getSuperclass()
                .getGenericSuperclass()).getActualTypeArguments()[0];
	}
	
	public T getById(Long id) {
        return (T) emp.get().find(persistentClass, id);
	}
	
	public List<T> findAll() {
		return emp.get().createQuery("select t from " + persistentClass.getName() + " t").getResultList();
	}	

	@Transactional
	public void save(T entity) {
		emp.get().persist(entity);
	}

	@Transactional
	public void remove(T entity) {
		emp.get().remove(entity);
	}

	protected EntityManager getEmp() {
		return emp.get();
	}
	
}